using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;

namespace Antix.Mail.Smtp
{
    public class MessageEventArgs : EventArgs
    {
        #region Constructor

        public MessageEventArgs(){
            _From = null;
            _To = new StringCollection();
            _Data = null;
        }

        #endregion

        #region constants etc

        public const string QUOTE_UTF8 = "=?utf-8?q?";
        public const string BASE64_UTF8 = "=?utf-8?b?";

        #endregion

        #region Properties

        private string _MessageId;

        public string MessageId
        {
            get { return _MessageId; }
        }

        private string _Subject;

        public string Subject
        {
            get { return _Subject; }
        }

        private string _From;

        public string From
        {
            get { return _From; }
            set{ _From = value; }
        }

        private StringCollection _To;

        public StringCollection To{
            get{ return _To; }
        }

        private string _Data;

        public string Data
        {
            get { return _Data; }
            set
            {
                _Data = value;

                // Get selected header values
                _MessageId = TextFunctions.Between(_Data, "message-id:", "\r\n", StringComparison.OrdinalIgnoreCase)
                    .Trim().TrimStart('<').TrimEnd('>');
                if (_MessageId == null || _MessageId.Length == 0)
                {
                    _MessageId = Guid.NewGuid().ToString();
                }
                _Subject = TextFunctions.Between(_Data, "subject:", "\r\n", StringComparison.OrdinalIgnoreCase).TrimStart();

                // check for special encoding
                if (_Subject.StartsWith(BASE64_UTF8, StringComparison.InvariantCultureIgnoreCase)) {
                    // subject has been encoded base 64
                    _Subject = Encoding.UTF8.GetString(
                        Convert.FromBase64String(_Subject.Substring(BASE64_UTF8.Length , _Subject.LastIndexOf("?=") - BASE64_UTF8.Length)));
                }

            }
        }

        #endregion
    }
}
